package com.youdianstar.app.ui

import android.Manifest
import android.content.Context
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.ImageSpan
import android.view.View
import androidx.core.content.ContextCompat
import com.youdianstar.app.BR
import com.youdianstar.app.R
import com.youdianstar.app.databinding.ActivityBranchDetailsBinding
import com.youdianstar.app.entity.BranchInfo
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.common.ConfigKey
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiStateObserver
import com.youdianstar.app.common.util.*
import com.youdianstar.app.common.util.dialog.DialogUtil

import com.gyf.immersionbar.ImmersionBar
import com.youdianstar.app.adapter.LogoBannerAdapter
import com.youdianstar.app.entity.BranchLogo
import com.youdianstar.app.util.DataHelperEx
import com.youdianstar.app.util.LatLngUtil
import com.youdianstar.app.util.MapJumpUtil
import com.youdianstar.app.common.ex.getViewColor
import com.zhpan.bannerview.constants.PageStyle
import com.youdianstar.app.common.auko.browse
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.*
import kotlin.collections.ArrayList


/**
 * File: BranchDetailActivity
 * Author: 82149 Create: 2021/11/10 18:01
 * Changes (from 2021/11/10)
 * --------------------------------------------------
 * description: 网点详情
 * ---------------------------------------------------
 *
 */
class BranchDetailActivity : BaseActivity<ActivityBranchDetailsBinding, BranchViewModel>() {
    override fun layoutId(): Int = R.layout.activity_branch_details

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): BranchViewModel {
        val model: BranchViewModel by viewModel()
        return model
    }

    private val bannerLogoList: MutableList<BranchLogo> = ArrayList()
//    var picDialog:Dialog?=null

    override fun initData() {
        super.initData()
        ImmersionBar.with(this).titleBarMarginTop(mBinding.ivBack).statusBarDarkFont(false).init()
        mBinding.ivBack.setThrottleListener {
            finish()
        }
        val id = intent.getIntExtra(Extra.IT_ID, 0)
        val distance = intent.getDoubleExtra(Extra.IT_DISTANCE, 0.0)

        mBinding.bannerLogos.setPageStyle(PageStyle.MULTI_PAGE_OVERLAP)
            .setCanLoop(false)
            .setIndicatorVisibility(View.GONE)
            .setLifecycleRegistry(lifecycle)
            .setAdapter(LogoBannerAdapter(this))
            .create(bannerLogoList)
//        mBinding.bannerLogos.removeDefaultPageTransformer()

        //1.读取本地定位点（localLat 和 localLng 现在是计算属性，会自动从 DataAppManager 获取最新位置，无需手动设置）
        //2.加载数据 - 传递distance参数
        mViewModel.getBranchDetails(id, distance)
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.detailLiveData.observe(this, object : BaseApiStateObserver<BranchInfo>(mBinding.lyContainer) {
                override fun onReload(v: View?) {}

                override fun onDataResult(data: BranchInfo?) {
                    super.onDataResult(data)
                    try {
                        data?.let {
                            setLayoutView(it)
                        }
                    } catch (e:Exception){
                        e.printStackTrace()
                    }
                }

                override fun onNetError(code: Int, e: String?) {
                    super.onNetError(code, e)
                }
            })
    }

    override fun initClickEvent() {
        mBinding.ivWeb.setThrottleListener {
            mViewModel.branchDetailFiled.get()?.let { info->
                if (info.website!=null){
                    val msg = getString(R.string.Dialog_ViewWeb)
                    showActionDialog(msg){
                       startWebAction(info.website)
                    }
                }
            }
        }

        mBinding.ivPhone.setThrottleListener {
            mViewModel.branchDetailFiled.get()?.let {
                it.landlinePhone?.let { phone->
                    val phoneCall = String.format(getString(R.string.Dialog_SelectCall_Message),phone)
                    showActionDialog(phoneCall) {
                        requestPermission(getString(R.string.Call_Permission_Tip), Manifest.permission.CALL_PHONE, granted = {
                            startCallAction()
                        })
                    }
                }
            }
        }

        mBinding.rlDistance.setThrottleListener {
            mViewModel.branchDetailFiled.get()?.let { data->
                val addressTx :String = if (!StrUtil.isEmpty(data.addressMap)) data.addressMap?:"" else data.address
                if (!StrUtil.isEmpty(addressTx)){
                    MapJumpUtil.jumpToGoogleMap(this, addressTx)
                }
            }
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        super.onPermissionsGranted(requestCode, perms)
        if (requestCode == REQUEST_PERMISSION_CODE)
            startCallAction()
    }

    /**调起拨号盘*/
    private fun startCallAction() {
        mViewModel.branchDetailFiled.get()?.let {
            if (it.landlinePhone != null)
                Tool.callPhone(this, it.landlinePhone)
        }
    }

    /**跳转外部浏览器*/
    private fun startWebAction(webStr:String) {
        if (webStr.startsWith("http"))
            browse(webStr)
        else {
            browse("https://$webStr")
        }
    }

    private fun showActionDialog(msg :String, confirmAction: (() -> Unit) = { }){
        DialogUtil.instance.showNotifyDialog(this,
            title = getString(R.string.public_notice),
            msg = msg,leftAction = {

            },left = getString(R.string.public_cancel),
            rightAction = confirmAction,
            right = getString(R.string.home_confirm),
            isShowLeft = true,isShowRight = true)
    }

    private fun setLayoutView(data: BranchInfo) {
        mViewModel.branchDetailFiled.set(data)
        //名称与地址
        mBinding.tvBranchName.text = data.branchName
        mBinding.tvBranchName.requestFocus()
        mBinding.tvAddress.text = data.address
//        val addressTx = createImageTextSpannable(this, data.address , R.drawable.icon_map_locations)
//        mBinding.tvAddress.text = addressTx
        //距离
        val distanceStr = LatLngUtil.getDistanceMiTx(data.lat, data.lng, mViewModel.localLat, mViewModel.localLng)
        mBinding.btnDistance.text = distanceStr
        //借还数量
        mBinding.tvRentAvailable.text = "${getString(R.string.home_rentTx)} ${data.rent}"
        mBinding.tvReturnAvailable.text = "${getString(R.string.home_returnTx)} ${data.recovery}"

        val isOnline :Boolean = data.isBusiness
        mBinding.tvBranchName.setTextColor(getViewColor(this,if (isOnline) R.color.color_39404D else R.color.color_888888))
        mBinding.tvOutLine.visibility = if (isOnline) View.GONE else View.VISIBLE
        mBinding.tvRentAvailable.visibility = if (isOnline) View.VISIBLE else View.INVISIBLE
        mBinding.tvReturnAvailable.visibility = if (isOnline) View.VISIBLE else View.INVISIBLE

        //营业时间 + 营业状态
        val isOpen :Boolean = data.isBusiness 
        val openTimeStr :String = data.openTime
        mBinding.tvOpenTime.text = openTimeStr
        if (isOpen){
            // 营业中 - 显示"服务中"状态
            mBinding.tvOpenTime.setTextColor(getViewColor(this, R.color.color_39404D))
            mBinding.tvOpenStatus.visibility = View.VISIBLE
            mBinding.tvOpenStatus.text = "服务中"
            mBinding.tvOpenStatus.setTextColor(Color.parseColor("#4ECDC4"))
        }else{
            // 未营业
            mBinding.tvOpenTime.setTextColor(getViewColor(this, R.color.color_888888))
            mBinding.tvOpenStatus.visibility = View.GONE
        }

        //联系电话
        mBinding.tvPhoneNumber.text = data.landlinePhone ?: "--"

        //计费规则 - 已移除，根据用户要求不显示
        // data.billing?.let {
        //     mBinding.tvPlanContent.text = DataHelperEx.pricePlanTx(this@BranchDetailActivity, it)
        // } ?: run { mBinding.tvPlanContent.text = "" }

        //图片 +图片列表
        data.images?.let {
            getBannerList(it)
        }

        mBinding.ivPhone.visibility = if (StrUtil.isEmpty(data.landlinePhone)) View.GONE else View.VISIBLE
        mBinding.ivWeb.visibility = if (StrUtil.isEmpty(data.website)) View.GONE else View.VISIBLE
    }

    /**获取图片列表*/
    private fun getBannerList(images: String) {
        bannerLogoList.clear()
        val list = listOf<String>(*images.split(",".toRegex()).toTypedArray())
        val host = DataAppManager.instance.getConfig(ConfigKey.FILE_HOST)
        if (list.isEmpty()){
            bannerLogoList.add(BranchLogo(0))
        }else{
            list.forEach { urlSt->
                bannerLogoList.add(BranchLogo(type = 1, url = (host + urlSt)))
            }
        }
        //更新Banner
        mBinding.bannerLogos.refreshData(bannerLogoList)
        mBinding.bannerLogos.currentItem = 0
    }

    /**
     * 拼接图 + 地址
     * @param text 文本
     */
    private fun createImageTextSpannable(mContext: Context, text: String, imageResId: Int): SpannableString {
        val spannable = SpannableString(text)
//        val bitmap: Bitmap = BitmapFactory.decodeResource(mContext.resources, imageResId)
        //图片放在开头
//        val imageSpan = ImageSpan(mContext, bitmap)
//        spannable.setSpan(imageSpan, 0, 0, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        ContextCompat.getDrawable(mContext, imageResId)?.let { drs->
            drs.setBounds(0, 0, drs.intrinsicWidth, drs.intrinsicHeight)
            val imageSpan = ImageSpan(drs, ImageSpan.ALIGN_BASELINE)
            spannable.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            //设置空格:缩进图片和空格宽度 (无效,图片会跟着缩进)
//            val leadingMarginSpan = LeadingMarginSpan.Standard(drs.intrinsicWidth + 6)//空格默认6像素
//            spannable.setSpan(leadingMarginSpan, 0, text.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        }
        return spannable
    }

    override fun onStop() {
        super.onStop()
        dismissDialog()
    }

}